<template>
  <el-container class="me-top">
    <el-header>
      <el-row>
        <el-col :span="18" style="text-align: left;">
          <el-form ref="form" :model="formInline" :inline="true">
            <el-form-item label="名称:">
              <el-input v-model="formInline.name" />
            </el-form-item>

            <el-button icon="el-icon-search" circle @click="search" />
          </el-form>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="add">添加</el-button>
          <el-popconfirm
            confirm-button-text="确认"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="确认全部删除？"
            @onConfirm="BatchRemove"
          >
            <el-button slot="reference" :disabled="flag" type="danger">批量删除</el-button>
          </el-popconfirm>
        </el-col>
      </el-row>
    </el-header>
    <el-main>
      <el-table
        :data="tableData"
        border stripe
        style="width: 100%" row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}" @selection-change="selectedRows">
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column prop="name" label="菜单名称" align="center" />
        <el-table-column prop="url" label="菜单地址" align="center" />
        <el-table-column prop="icon" label="菜单图标" align="center">
          <template slot-scope="scope">
            <i  :class="scope.row.icon" style="font-size: 20px" />
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" align="center" width="200">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit-outline" @click="edit(scope.row)">编辑</el-button>
            <el-popconfirm
              confirm-button-text="确认"
              cancel-button-text="取消"
              icon="el-icon-info"
              icon-color="red"
              title="你确定要删除当前数据？"
              @onConfirm="remove(scope.row)"
            >
              <el-button slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div class="block">
        <el-pagination
          :page-sizes="pageSizes"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-main>
    <!--  新增、编辑-->
    <el-dialog title="新增菜单" center width="23%" :visible.sync="dialogFormVisible">
      <el-form ref="addForm" :model="addForm" label-width="100px" status-icon :rules="rules">
        <input v-model="addForm.id" type="hidden">
        <el-form-item prop="name" label="菜单名称：">
          <el-input v-model="addForm.name" clearable />
        </el-form-item>
        <el-form-item prop="url"  label="菜单地址：">
          <el-input v-model="addForm.url" clearable  />
        </el-form-item>
        <el-form-item prop="icon " label="菜单图标：">
          <e-icon-picker v-model="addForm.icon"  />
        </el-form-item>
        <el-form-item prop="parentId" label="父菜单：">
          <el-cascader placeholder="可搜索关键字"
                       filterable @change="getMenuParentId"
                       :props="{ checkStrictly: true }"
                       :options="options" clearable style="width: 200px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </el-container>

</template>

<script>
export default {
  data() {
    return {
      flag: true,
      addForm: {
        id: '',
        name: '',
        url: '',
        icon: '',
        parentId : ''
      },
      page: 1, // 第几页
      size: 10, // 每页条数
      total: 0,
      pageSizes: [5, 10, 15, 20],
      tableData: [],
      formInline: {
        name: '',
        date: ''
      },
      dialogFormVisible: false,
      selectRows: {},
      options : [],
      menuParent : [],
      rules: {
        name: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        /*url: [
          { required: true, message: '请输入菜单地址', trigger: 'blur' }
        ]*/
      }
    }
  },
  mounted() {
    this.loadListData()
  },
  methods: {
    getMenuParentId(value) {
      // this.menuParent = value[value.length-1]
      this.menuParent = value
    },
    search() {
      this.loadListData()
    },
    submit() {
      const axios = this.$http // 定义请求
      const msg = this.$message // 定义消息弹框
      if (this.addForm.id) { // 修改
        this.addForm.parentId = this.menuParent[this.menuParent.length-1]
        axios.put('/menu/update', this.addForm).then((res) => {
          if (res.data.success) {
            msg.success(res.data.message)
            this.loadListData()
            this.dialogFormVisible = false
          } else {
            // eslint-disable-next-line no-undef
            msg.error('修改失败[' + error.message + ']')
          }
        }).catch(error => {
          console.log(error)
        })
      } else { // 添加
        const axios = this.$http // 定义请求
        const msg = this.$message // 定义消息弹框
        axios.post('/menu/insert', this.addForm).then((res) => {
          if (res.data.success) {
            this.$notify({ title: '添加失败',  message: res.data.message ,  type: 'warning' });
            this.loadListData()
            this.dialogFormVisible = false
          } else {
          // eslint-disable-next-line no-undef
            this.$notify({ title: '添加失败',  message: res.data.message ,  type: 'warning' });
          }
        }).catch(error => {
          console.log(error)
        })
      }
    },
    add() {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields()
      })
      for(let key in this.addForm){
        this.addForm[key] = ''
      }
    },
    edit(row) {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.addForm = Object.assign({}, row)
      })
    },
    remove(row) {
      const axios = this.$http // 定义请求
      const msg = this.$message // 定义消息弹框
      axios.delete('/menu/deleteById/' + row.id).then(res => {
        if (res.data.success) {
          msg.success(res.data.message)
          this.loadListData()
        } else {
          // eslint-disable-next-line no-undef
          this.$notify({ title: '删除失败',  message: res.data.message ,  type: 'warning' });
        }
      }).catch(error => {
        msg.error('删除失败[' + error.message + ']')
      })
    },
    BatchRemove() {
      const axios = this.$http // 定义请求
      const msg = this.$message // 定义消息弹框
      const ids = this.selectRows.map(function(obj, index, arr) {
        return obj.id
      })
      console.log(ids.toString())
      axios.post('/menu/batchDeleteByIds', { ids: ids }).then(res => {
        if (res.data.success) {
          msg.success(res.data.message)
          this.loadListData()
        } else {
        // eslint-disable-next-line no-undef
          msg.error('删除失败[' + error.message + ']')
        }
      }).catch(error => {
        msg.error('删除失败[' + error.message + ']')
      })
    },
    handleSizeChange(val) {
      this.size = val
      this.loadListData()
    },
    handleCurrentChange(currentPage) {
      this.page = currentPage
      this.loadListData()
    },
    loadListData() {
      const axios = this.$http // 定义请求
      this.loading = true
      // vue加载完成，发送ajax请求动态获取数据
      const param = {
        'pageNo': this.page,
        'pageSize': this.size,
        'keyWord': this.formInline.name
      }
      axios.post('/menu/findForList', param).then((res) => {
        this.tableData = res.data.data.result
        this.total = res.data.data.total
        this.page = res.data.data.pageNo
        this.options = [] //清出之前的数据
        this.menuJsonConvert(this.tableData)
      }).catch(error => {
        console.log(error)
      })
    },
    selectedRows(rows) {
      console.log(rows)
      if (rows.length > 0) {
        this.flag = false
        this.selectRows = rows
      } else {
        this.flag = true
      }
    },
    menuJsonConvert(json){
      let selectData = json
      for (let i = 0; i < selectData.length; i++) {
        let options = {}
        options["value"] = selectData[i].id
        options["label"] = selectData[i].name
        if (selectData[i].children){
          options["children"] = []
          for (let j = 0; j < selectData[i].children.length ; j++) {
              options["children"].push({"value":selectData[i].children[j].id,"label":selectData[i].children[j].name})
              this.menuJsonConvert(selectData[i].children[j].children)
          }
        }
        this.options.push(options);
      }
    }
  }
}
</script>

<style scoped>
.me-top{
  padding-top: 20px;
}
</style>
